<script setup lang="ts" name="emergency-group">
import {
  getCurrentInstance,
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  saveGroup,
  getGroupList,
  deleteGroup,
  getGroupUserList,
  saveGroupUser,
  deleteGroupUser,
  getGroupUserTasks,
  getUserList,
} from "@/api/server_emergency";
const router = useRouter();
const height = ref(200);

const groupUserList = ref<any[]>([]);
const userListTotal = ref(0);
let userListForm = ref<any>({
  page: 1,
  pageSize: 20,
});
const activeInfo = ref<any>({});
const groupList = ref<any>([]);
const userList = ref<any>([]);
const userDialogVisible = ref(false);
const taskDialogVisible = ref(false);
const addUserItem = ref<any>({});
const tasksList = ref<any>([]);

const handleCurrentChange = (page: number) => {
  userListForm.page = page;
  getGroupUserList_(page);
};
const getUserList_ = async () => {
  let res = await getUserList({
    page: 1,
    pageSize: 10000,
  });
  userList.value = res.list;
  console.log("userList.value", userList.value);
};
const getGroupList_ = async () => {
  let res: any = await getGroupList({});
  groupList.value = res.groupList;

  if (!activeInfo) {
    activeInfo.value = res.groupList[0];
    getGroupUserList_(1);
  }
  console.log('测试执行',activeInfo.value.emergency_group_id);
};

const editGroup = (data: any) => {
  ElMessageBox.prompt(
    `${data.emergency_group_id ? "编辑" : "新增"}应急组`,
    "",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputValue: data.name,
      // inputPattern: /^.{1,100}$/,
      // inputErrorMessage: "请输入内容",
    }
  )
    .then(async ({ value }) => {
      let res = await saveGroup({
        id: data.emergency_group_id || 0,
        name: value,
        status: "normal",
      });
      if (res.result == "success") {
        getGroupList_();
      }
    })
    .catch(() => {});
};
const deleteGroup_ = (data: any) => {
  ElMessageBox.confirm(
    `<span>确定要删除 <i style="color:#58B2C5;">${data.name}</i> 吗</span>`,
    "提 示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      type: "warning",
    }
  ).then(async () => {
    let res = await deleteGroup({
      id: data.emergency_group_id,
    });
    if (res.result == "success") {
      getGroupList_();
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
};

const handleCommand = (command: string | number | object, data: object) => {
  if (command === "edit") {
    editGroup(data);
  }
  if (command === "delete") {
    deleteGroup_(data);
  }
};
const tabGroup = async (item: any) => {
  console.log('item',item);
  
  activeInfo.value = item;
  getGroupUserList_(1);
};
const getGroupUserList_ = async (page: number) => {
  let res = await getGroupUserList({
    groupId: activeInfo.value.emergency_group_id,
    page: page || 1,
    tasks: [],
  });
  groupUserList.value = res.list || [];
  userListTotal.value = res.total || 1;
  console.log("res", res);
};
const addUser = async () => {
  userDialogVisible.value = true;
  addUserItem.value.tasks = [""];
};
const saveUser = async () => {
  let res = await saveGroupUser({
    groupId: activeInfo.value.emergency_group_id,
    ...addUserItem.value,
  });

  if (res.result == "success") {
    userDialogVisible.value = false;
    getGroupList_();
    getGroupUserList_(1);
  }
};

const groupUserTasks = async (item: any) => {
  let res = await getGroupUserTasks({
    groupId: activeInfo.value.emergency_group_id,
    userId: item.user_id,
  });
  return res.groupUserTasks;
};
const taskInfo = async (item: any) => {
  tasksList.value = [];
  taskDialogVisible.value = true;
  let tasks = await groupUserTasks(item);
  tasksList.value = tasks;
};
const editUser = async (item: any) => {
  userDialogVisible.value = true;
  addUserItem.value.userId = item.user_id;
  addUserItem.value.tasks = [];
  let tasks = await groupUserTasks(item);
  let taskContent = tasks.map((v: any) => v.content);
  addUserItem.value.tasks = taskContent;
};
const deleteUser = async (item: any) => {
  let res = await deleteGroupUser({
    groupUserId: item.emergency_group_user_id,
  });
  getGroupUserList_(userListForm.value.page);
  getGroupList_();
};
onMounted(() => {
  setTimeout(() => {
    let pageTable: any = document.querySelector(".page-table");
    height.value = pageTable.clientHeight;
  }, 50);
  getUserList_();
  getGroupList_();
});
</script>

<template>
  <div class="emergency-group">
    <div class="page-top">
      <h4>应急组配置</h4>
    </div>
    <div class="group-info">
      <div class="group-left">
        <div
          class="group-name-item"
          @click="tabGroup(item)"
          :class="{
            active: activeInfo.emergency_group_id == item.emergency_group_id,
          }"
          :key="index"
          v-for="(item, index) in groupList"
        >
          <span>{{ item.name }}({{ item.cnt }})</span>
          <el-dropdown @command="handleCommand($event, item)">
            <el-icon><MoreFilled /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="group-name-add" @click="editGroup({})">
          <el-icon><Plus /></el-icon>
          <span>新增应急组</span>
        </div>
      </div>
      <div class="group-right">
        <div class="page-top">
          <h4>{{ activeInfo.name }}</h4>
          <el-button type="primary" size="small" @click="addUser"
            >新增人员</el-button
          >
        </div>
        <div class="page-table">
          <el-table :data="groupUserList" :height="height" size="small" border>
            <el-table-column
              label="序号"
              width="100"
              prop="emergency_group_user_id"
            ></el-table-column>
            <el-table-column
              label="姓名"
              prop="userInfo.name"
            ></el-table-column>
            <el-table-column
              label="电话"
              prop="userInfo.phone"
            ></el-table-column>
            <el-table-column
              label="部门"
              prop="userInfo.deptName"
            ></el-table-column>
            <el-table-column label="操作" prop="">
              <template #default="scope">
                <el-button link size="small" @click="taskInfo(scope.row)"
                  >任务详情</el-button
                >
                <el-button link size="small" @click="editUser(scope.row)"
                  >编辑</el-button
                >
                <el-button link size="small" @click="deleteUser(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          style="text-align: right"
          layout="prev, pager, next"
          :page-size="20"
          @current-change="handleCurrentChange"
          v-model:currentPage="userListForm.page"
          :total="userListTotal"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :title="`添加用户`"
      v-model="userDialogVisible"
      width="500px"
    >
      <el-form
        :model="addUserItem"
        size="small"
        label-width="120px"
        class="warning-form-inline"
      >
        <el-form-item label="添加用户">
          <el-select
            filterable
            clearable
            style="width: 80%"
            v-model="addUserItem.userId"
            placeholder="请选择"
          >
            <el-option
              :value="c.user_id"
              :label="c.name"
              :key="index"
              v-for="(c, index) in userList"
            >
              <span style="float: left">{{ c.name }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
                >{{ c.phone }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="`任务${index + 1}`"
          :key="index"
          v-for="(item, index) in addUserItem.tasks || []"
        >
          <el-input
            v-model="addUserItem.tasks[index]"
            :rows="3"
            type="textarea"
            placeholder="请输入任务情况"
          />
        </el-form-item>
        <el-form-item label="">
          <div class="group-add-task" @click="addUserItem.tasks.push('')">
            <el-icon><Plus /></el-icon>
            <span>新增任务</span>
          </div>
        </el-form-item>

        <el-form-item>
          <div style="text-align: right">
            <el-button @click="userDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveUser">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="任务详情"
      v-model="taskDialogVisible"
      width="500px"
    >
      <div style="max-height: 500px; overflow: auto">
        <div
          style="margin: 10px 5px"
          v-for="(item, index) in tasksList || []"
          :key="index"
        >
          <h3 style="">任务{{ index + 1 }}</h3>
          <div style="font-weight: bold">{{ item.content }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.emergency-group {
  width: 100%;
  height: 100%;
  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .group-info {
    height: calc(100% - 30px);
    display: flex;
    align-items: center;
    .group-left {
      height: 100%;
      width: 240px;
      flex-shrink: 0;
      overflow-x: hidden;
      overflow-y: auto;
      border: 1px solid #414243;
      .group-name-item {
        width: 240px;
        height: 40px;
        line-height: 40px;
        position: relative;
        padding: 0 30px;
        cursor: pointer;
        &.active {
          background: #3f74a694;
        }
        .el-dropdown {
          transform: rotate(90deg);
          position: absolute;
          right: 5px;
          top: 10px;
          cursor: pointer;
        }
      }
      .group-name-add {
        width: 192px;
        height: 40px;
        line-height: 40px;
        margin: 10px auto;
        border: 1px dashed #d9d9d9;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    }
    .group-right {
      height: 100%;
      flex: 1;
      padding: 0 10px;
      .page-table {
        margin-top: 10px;
        height: calc(100% - 80px);
      }
    }
  }
}
.group-add-task {
  width: 180px;
  height: 30px;
  line-height: 40px;
  margin: 10px 0;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>
